/*!
 * \file test_charconv_comprehensive.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/19
 * 
 * \brief 字符转换工具综合测试文件
 * 测试字符串转换、编码转换等功能
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <atomic>
#include <limits>
#include <locale>
#include <codecvt>
#include <sstream>
#include <iomanip>

// 字符转换相关的测试，覆盖常见的字符串处理场景

/**
 * 字符转换综合测试类
 * 测试各种字符串转换和编码功能
 */
class CharConvComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 初始化测试数据
        test_strings_ = {
            "hello", "world", "123", "456.789",
            "Hello World", "测试字符串", "Test String",
            "", " ", "  ", "\t", "\n", "\r\n"
        };
        
        test_numbers_ = {
            0, 1, -1, 123, -456, 999999, -999999,
            std::numeric_limits<int>::max(),
            std::numeric_limits<int>::min()
        };
        
        test_floats_ = {
            0.0, 1.0, -1.0, 123.456, -789.123,
            std::numeric_limits<double>::max(),
            std::numeric_limits<double>::lowest(),
            std::numeric_limits<double>::epsilon()
        };
    }

    void TearDown() override {
        // 清理测试环境
    }

    std::vector<std::string> test_strings_;
    std::vector<int> test_numbers_;
    std::vector<double> test_floats_;
};

/**
 * 测试基本的字符串转数字功能
 */
TEST_F(CharConvComprehensiveTest, TestStringToNumber) {
    // 测试字符串转整数
    EXPECT_EQ(std::stoi("123"), 123);
    EXPECT_EQ(std::stoi("-456"), -456);
    EXPECT_EQ(std::stoi("0"), 0);
    
    // 测试字符串转浮点数
    EXPECT_DOUBLE_EQ(std::stod("123.456"), 123.456);
    EXPECT_DOUBLE_EQ(std::stod("-789.123"), -789.123);
    EXPECT_DOUBLE_EQ(std::stod("0.0"), 0.0);
    
    // 测试科学计数法
    EXPECT_DOUBLE_EQ(std::stod("1.23e2"), 123.0);
    EXPECT_DOUBLE_EQ(std::stod("1.23e-2"), 0.0123);
}

/**
 * 测试数字转字符串功能
 */
TEST_F(CharConvComprehensiveTest, TestNumberToString) {
    // 测试整数转字符串
    EXPECT_EQ(std::to_string(123), "123");
    EXPECT_EQ(std::to_string(-456), "-456");
    EXPECT_EQ(std::to_string(0), "0");
    
    // 测试浮点数转字符串
    std::string float_str = std::to_string(123.456);
    EXPECT_TRUE(float_str.find("123.456") != std::string::npos);
    
    // 测试格式化转换
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(2) << 123.456;
    EXPECT_EQ(oss.str(), "123.46");
}

/**
 * 测试字符串大小写转换
 */
TEST_F(CharConvComprehensiveTest, TestCaseConversion) {
    std::string test_str = "Hello World";
    
    // 转换为大写
    std::string upper_str = test_str;
    std::transform(upper_str.begin(), upper_str.end(), upper_str.begin(), ::toupper);
    EXPECT_EQ(upper_str, "HELLO WORLD");
    
    // 转换为小写
    std::string lower_str = test_str;
    std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), ::tolower);
    EXPECT_EQ(lower_str, "hello world");
    
    // 测试空字符串
    std::string empty_str = "";
    std::transform(empty_str.begin(), empty_str.end(), empty_str.begin(), ::toupper);
    EXPECT_EQ(empty_str, "");
}

/**
 * 测试字符串修剪功能
 */
TEST_F(CharConvComprehensiveTest, TestStringTrimming) {
    // 左修剪函数
    auto ltrim = [](std::string s) {
        s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
            return !std::isspace(ch);
        }));
        return s;
    };
    
    // 右修剪函数
    auto rtrim = [](std::string s) {
        s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
            return !std::isspace(ch);
        }).base(), s.end());
        return s;
    };
    
    // 双向修剪函数
    auto trim = [&](std::string s) {
        return ltrim(rtrim(s));
    };
    
    // 测试修剪功能
    EXPECT_EQ(trim("  hello  "), "hello");
    EXPECT_EQ(trim("\t\nworld\r\n"), "world");
    EXPECT_EQ(trim("   "), "");
    EXPECT_EQ(trim("no_spaces"), "no_spaces");
}

/**
 * 测试字符串分割功能
 */
TEST_F(CharConvComprehensiveTest, TestStringSplitting) {
    // 字符串分割函数
    auto split = [](const std::string& str, char delimiter) {
        std::vector<std::string> tokens;
        if (str.empty()) {
            return tokens; // 返回空向量而不是包含空字符串的向量
        }
        std::stringstream ss(str);
        std::string token;
        while (std::getline(ss, token, delimiter)) {
            tokens.push_back(token);
        }
        return tokens;
    };
    
    // 测试分割功能
    auto result1 = split("a,b,c", ',');
    EXPECT_EQ(result1.size(), 3);
    EXPECT_EQ(result1[0], "a");
    EXPECT_EQ(result1[1], "b");
    EXPECT_EQ(result1[2], "c");
    
    auto result2 = split("hello world test", ' ');
    EXPECT_EQ(result2.size(), 3);
    EXPECT_EQ(result2[0], "hello");
    EXPECT_EQ(result2[1], "world");
    EXPECT_EQ(result2[2], "test");
    
    // 测试空字符串
    auto result3 = split("", ',');
    EXPECT_EQ(result3.size(), 0);
}

/**
 * 测试字符串连接功能
 */
TEST_F(CharConvComprehensiveTest, TestStringJoining) {
    // 字符串连接函数
    auto join = [](const std::vector<std::string>& strings, const std::string& delimiter) {
        if (strings.empty()) return std::string();
        
        std::ostringstream oss;
        for (size_t i = 0; i < strings.size(); ++i) {
            if (i > 0) oss << delimiter;
            oss << strings[i];
        }
        return oss.str();
    };
    
    // 测试连接功能
    std::vector<std::string> tokens1 = {"a", "b", "c"};
    EXPECT_EQ(join(tokens1, ","), "a,b,c");
    EXPECT_EQ(join(tokens1, " "), "a b c");
    
    std::vector<std::string> tokens2 = {"hello", "world"};
    EXPECT_EQ(join(tokens2, " "), "hello world");
    
    // 测试空向量
    std::vector<std::string> empty_tokens;
    EXPECT_EQ(join(empty_tokens, ","), "");
}

/**
 * 测试字符串替换功能
 */
TEST_F(CharConvComprehensiveTest, TestStringReplacement) {
    // 字符串替换函数
    auto replace_all = [](std::string str, const std::string& from, const std::string& to) {
        if (from.empty()) return str; // 防止空字符串导致无限循环
        size_t start_pos = 0;
        while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
            str.replace(start_pos, from.length(), to);
            start_pos += to.length();
        }
        return str;
    };
    
    // 测试替换功能
    EXPECT_EQ(replace_all("hello world", "world", "universe"), "hello universe");
    EXPECT_EQ(replace_all("aaa", "a", "b"), "bbb");
    EXPECT_EQ(replace_all("abc abc abc", "abc", "xyz"), "xyz xyz xyz");
    
    // 测试空字符串替换
    EXPECT_EQ(replace_all("hello", "", "x"), "hello");
    EXPECT_EQ(replace_all("", "a", "b"), "");
}

/**
 * 测试字符编码转换
 */
TEST_F(CharConvComprehensiveTest, TestCharacterEncoding) {
    // 测试ASCII字符
    std::string ascii_str = "Hello World 123";
    EXPECT_TRUE(std::all_of(ascii_str.begin(), ascii_str.end(), [](unsigned char c) {
        return c < 128;
    }));
    
    // 测试UTF-8字符串长度计算
    std::string utf8_str = "测试";
    EXPECT_GT(utf8_str.length(), 2); // UTF-8编码的中文字符占用多个字节
    
    // 测试字符分类
    EXPECT_TRUE(std::isalpha('a'));
    EXPECT_TRUE(std::isdigit('1'));
    EXPECT_TRUE(std::isspace(' '));
    EXPECT_TRUE(std::ispunct(','));
}

/**
 * 测试十六进制转换
 */
TEST_F(CharConvComprehensiveTest, TestHexadecimalConversion) {
    // 整数转十六进制
    std::ostringstream hex_stream;
    hex_stream << std::hex << 255;
    EXPECT_EQ(hex_stream.str(), "ff");
    
    // 十六进制转整数
    int hex_value;
    std::istringstream("ff") >> std::hex >> hex_value;
    EXPECT_EQ(hex_value, 255);
    
    // 测试大写十六进制
    std::ostringstream upper_hex_stream;
    upper_hex_stream << std::uppercase << std::hex << 255;
    EXPECT_EQ(upper_hex_stream.str(), "FF");
}

/**
 * 测试二进制转换
 */
TEST_F(CharConvComprehensiveTest, TestBinaryConversion) {
    // 整数转二进制字符串
    auto to_binary = [](int n) {
        std::string binary;
        if (n == 0) return std::string("0");
        
        while (n > 0) {
            binary = (n % 2 ? "1" : "0") + binary;
            n /= 2;
        }
        return binary;
    };
    
    EXPECT_EQ(to_binary(5), "101");
    EXPECT_EQ(to_binary(8), "1000");
    EXPECT_EQ(to_binary(0), "0");
    
    // 二进制字符串转整数
    auto from_binary = [](const std::string& binary) {
        int result = 0;
        for (char c : binary) {
            result = result * 2 + (c - '0');
        }
        return result;
    };
    
    EXPECT_EQ(from_binary("101"), 5);
    EXPECT_EQ(from_binary("1000"), 8);
    EXPECT_EQ(from_binary("0"), 0);
}

/**
 * 测试字符串验证功能
 */
TEST_F(CharConvComprehensiveTest, TestStringValidation) {
    // 数字字符串验证
    auto is_numeric = [](const std::string& str) {
        if (str.empty()) return false;
        size_t start = 0;
        if (str[0] == '-' || str[0] == '+') start = 1;
        if (start >= str.length()) return false;
        
        bool has_dot = false;
        for (size_t i = start; i < str.length(); ++i) {
            if (str[i] == '.') {
                if (has_dot) return false;
                has_dot = true;
            } else if (!std::isdigit(str[i])) {
                return false;
            }
        }
        return true;
    };
    
    EXPECT_TRUE(is_numeric("123"));
    EXPECT_TRUE(is_numeric("-456"));
    EXPECT_TRUE(is_numeric("123.456"));
    EXPECT_TRUE(is_numeric("+789"));
    EXPECT_FALSE(is_numeric("abc"));
    EXPECT_FALSE(is_numeric("12.34.56"));
    EXPECT_FALSE(is_numeric(""));
    
    // 邮箱格式验证（简单版本）
    auto is_email = [](const std::string& str) {
        size_t at_pos = str.find('@');
        if (at_pos == std::string::npos || at_pos == 0 || at_pos == str.length() - 1) {
            return false;
        }
        size_t dot_pos = str.find('.', at_pos);
        return dot_pos != std::string::npos && dot_pos < str.length() - 1;
    };
    
    EXPECT_TRUE(is_email("test@example.com"));
    EXPECT_TRUE(is_email("user@domain.org"));
    EXPECT_FALSE(is_email("invalid.email"));
    EXPECT_FALSE(is_email("@example.com"));
    EXPECT_FALSE(is_email("test@"));
}

/**
 * 测试字符串性能特征
 */
TEST_F(CharConvComprehensiveTest, TestPerformanceCharacteristics) {
    const int iterations = 10000;
    std::vector<std::string> test_data;
    
    // 生成测试数据
    for (int i = 0; i < iterations; ++i) {
        test_data.push_back("test_string_" + std::to_string(i));
    }
    
    auto start = std::chrono::high_resolution_clock::now();
    
    // 执行字符串操作
    std::string result;
    for (const auto& str : test_data) {
        result += str + "_processed";
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    // 验证结果
    EXPECT_FALSE(result.empty());
    EXPECT_LT(duration.count(), 1000000); // 应该在1秒内完成
    
    std::cout << "字符串操作性能: " << iterations << " 次操作耗时 " 
              << duration.count() << " 微秒" << std::endl;
}

/**
 * 测试多线程环境下的字符串操作
 */
TEST_F(CharConvComprehensiveTest, TestMultiThreadStringOperations) {
    const int num_threads = 4;
    const int operations_per_thread = 1000;
    std::vector<std::thread> threads;
    std::atomic<int> success_count(0);
    
    for (int t = 0; t < num_threads; ++t) {
        threads.emplace_back([&, t]() {
            for (int i = 0; i < operations_per_thread; ++i) {
                std::string test_str = "thread_" + std::to_string(t) + "_op_" + std::to_string(i);
                std::string upper_str = test_str;
                std::transform(upper_str.begin(), upper_str.end(), upper_str.begin(), ::toupper);
                
                if (!upper_str.empty() && upper_str.length() == test_str.length()) {
                    success_count.fetch_add(1);
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证结果
    int expected_success = num_threads * operations_per_thread;
    EXPECT_EQ(success_count.load(), expected_success);
    
    std::cout << "多线程字符串测试结果: " << success_count.load() 
              << "/" << expected_success << " 次操作成功" << std::endl;
}

/**
 * 测试错误处理和边界条件
 */
TEST_F(CharConvComprehensiveTest, TestErrorHandlingAndBoundaryConditions) {
    // 测试无效的数字转换
    try {
        std::stoi("invalid_number");
        FAIL() << "应该抛出异常";
    } catch (const std::invalid_argument&) {
        // 预期的异常
    }
    
    try {
        std::stoi("999999999999999999999"); // 超出int范围
        FAIL() << "应该抛出异常";
    } catch (const std::out_of_range&) {
        // 预期的异常
    }
    
    // 测试空字符串处理
    EXPECT_TRUE(std::string().empty());
    EXPECT_EQ(std::string().length(), 0);
    
    // 测试非常长的字符串
    std::string long_string(10000, 'a');
    EXPECT_EQ(long_string.length(), 10000);
    EXPECT_TRUE(std::all_of(long_string.begin(), long_string.end(), [](char c) {
        return c == 'a';
    }));
}

/**
 * 测试完整的字符转换工作流程
 */
TEST_F(CharConvComprehensiveTest, TestCompleteWorkflow) {
    // 模拟完整的字符串处理流程
    
    // 1. 输入数据
    std::vector<std::string> input_data = {
        "  Hello World  ", "123.456", "TEST_STRING", "mixed123CASE"
    };
    
    // 2. 数据清理和转换
    std::vector<std::string> processed_data;
    for (const auto& str : input_data) {
        // 修剪空白字符
        std::string trimmed = str;
        trimmed.erase(0, trimmed.find_first_not_of(" \t\n\r"));
        trimmed.erase(trimmed.find_last_not_of(" \t\n\r") + 1);
        
        // 转换为小写
        std::transform(trimmed.begin(), trimmed.end(), trimmed.begin(), ::tolower);
        
        processed_data.push_back(trimmed);
    }
    
    // 3. 验证处理结果
    EXPECT_EQ(processed_data.size(), input_data.size());
    EXPECT_EQ(processed_data[0], "hello world");
    EXPECT_EQ(processed_data[1], "123.456");
    EXPECT_EQ(processed_data[2], "test_string");
    EXPECT_EQ(processed_data[3], "mixed123case");
    
    // 4. 生成报告
    std::ostringstream report;
    report << "处理了 " << input_data.size() << " 个字符串:\n";
    for (size_t i = 0; i < input_data.size(); ++i) {
        report << "原始: \"" << input_data[i] << "\" -> 处理后: \"" << processed_data[i] << "\"\n";
    }
    
    std::string report_str = report.str();
    EXPECT_FALSE(report_str.empty());
    EXPECT_TRUE(report_str.find("处理了") != std::string::npos);
    
    std::cout << "字符转换工作流程测试完成:\n" << report_str << std::endl;
} 